﻿/*
	Class: DocElemTemplate
	
		This class handles the <template /> tag.
*/
package com.frontalcode 
{
	import flash.utils.*;

	/**
	 * The DocElemInclude class handles the <template /> tag.
	 */
    public class DocElemTemplate extends DocumentElement
    {
		static private var allTemplates : Dictionary = new Dictionary ( true );
		private var _template : XMLList;
		
		/**
		 * Creates a new DocElemTemplate instance.
		 * 
		 * @param document	The document this element belongs to.
		 * @param parent	The element's parent in the document tree.
		 * @param node		The XML node this element is associated with.
		 * @param options	Options affecting the behavior of this instance.
		 * 					(This object does not have built-in support for any
		 * 					options.)
		 */
		public function DocElemTemplate ( document : Document, parent : DocumentElement, node : XML, options : Object = null )
		{
			super ( document, parent, node, options );
			
			processesOwnContent = true;
			
			if ( allTemplates [ document ] == null ) allTemplates [ document ] = { };
			
			// Remove our XML children from the document and store as our 
			// template.
			//
			_template = node.children ( );
			delete node.*;
			
			if ( node.@name != undefined ) 
			{
				if ( allTemplates [ document ] [ node.@name ] == null ) allTemplates [ document ] [ node.@name ] = [ ];
				allTemplates [ document ] [ node.@name ].push ( _template );
			}
		}
		
		/**
		 * @private
		 */
		static internal function onDestroyDocument ( document : Document ) : void { delete allTemplates [ document ]; }
		
		/**
		 * @private
		 */
		override public function destroy ( ) : void 
		{ 
			super.destroy ( );
			
			if ( node.@name != undefined && allTemplates [ document ] [ node.@name ] != null )
			{
				var index : int = allTemplates [ document ] [ node.@name ].indexOf ( template );
				if ( index >= 0 ) allTemplates [ document ] [ node.@name ].splice ( index, 1 );
			}
		}
		
		public function get template ( ) : XMLList { return _template; }
		
		/**
		 * @private
		 */
		static internal function getTemplateByName ( document : Document, name : String ) : XMLList
		{
			var docTemplate : Object = allTemplates [ document ];
			if ( docTemplate == null ) return null;
			return docTemplate [ name ] != null && docTemplate [ name ].length > 0 ? docTemplate [ name ] [ docTemplate [ name ].length - 1 ] : null;
		}
		
		/**
		 * @private
		 */
		override public function get needsRender ( ) : Boolean 
		{ 
			if ( getStyle ( "disable-rendering" ) === undefined ) return false;
			return super.needsRender; 
		}
	}
}
